﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Plugin.Upload.Models;

namespace Plugin.Upload.Controllers
{
 
    [Route("api/[controller]")]
    [ApiController]
    public class StorageController : ControllerBase
    {
       
        public StorageController(
            
        )
        {

            
        }

      
        [Authorize("admin")]
        [HttpPost("local")]
        public async Task<object> UpToken()
        {
            var files = Request.Form.Files;
         
            if (files == null || files.Count == 0)
            {
                return BadRequest("没有选择文件");
            }
            var dir= Path.Combine(AppContext.BaseDirectory, "wwwroot", "public");
            if(!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            List<UploadResultDto> target = new List<UploadResultDto>();

            foreach (var item in files)
            {
                // 指定文件保存的路径
                var fileName = $"{Guid.NewGuid().ToString("N")}.{item.FileName.Split(".")[1]}";
                var filePath = Path.Combine(dir,fileName);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await item.CopyToAsync(stream);
                }
                target.Add(new UploadResultDto
                {
                    Key = $"/public/{fileName}",
                    Url= $"{Request.Scheme}://{Request.Host}/public/{fileName}"
                }) ;
            }


            return target;
        }



    }
}



